package com.app.couponsharelife.ui.main.me.profit.fragment

import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gavin.com.library.PowerfulStickyDecoration
import com.gavin.com.library.listener.PowerGroupListener
import com.makeramen.roundedimageview.RoundedImageView
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.EarningsRecord
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.UserEarningsBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.listener.MyMultiPurposeListener
import com.app.couponsharelife.ui.main.me.profit.record.ProfitRecordActivity
import com.app.couponsharelife.utils.AppUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.base_refresh_head.*
import kotlinx.android.synthetic.main.fragment_online_profit.*
import kotlinx.android.synthetic.main.profit_list_rvtop.view.*
import kotlinx.android.synthetic.main.profit_record_item.view.*
import java.text.SimpleDateFormat
import java.util.*

/**
 *Created by xct on 2019/2/22
 *Description:线上收益列表
 */
class OnlineProfitFragment:LazyFragment() {
    private var pageIndex=1
    private var dataList= arrayListOf<EarningsRecord>()
    private var adapter:MyAdapter?=null
    private var time=""
    private var decoration:PowerfulStickyDecoration?=null
    val simpleDateFormat = SimpleDateFormat("yyyy-MM", Locale.getDefault())
    companion object {
        fun newInstance(): OnlineProfitFragment {
            val fragment = OnlineProfitFragment()
            fragment.arguments = Bundle()
            return fragment
        }
    }
    override val viewLayoutId: Int
        get() = R.layout.fragment_online_profit

    override fun initViews() {
        setRefresh()
        adapter=MyAdapter()
        onlineProfit_rv.layoutManager=LinearLayoutManager(activity)
        val listener=object : PowerGroupListener{
            override fun getGroupName(position: Int): String {
                return dataList[position].headTime
            }
            override fun getGroupView(position: Int): View {
                val view=LayoutInflater.from(activity).inflate(R.layout.profit_list_rvtop, null, false)
                view.profitList_tvTime.text=dataList[position].headTime
                //Log.e("eeee","---->"+dataList[position].createTime)
                view.profitList_tvPrice.text="结算收益 ¥"+dataList[position].totalMoney
                return view
            }
        }
        decoration= PowerfulStickyDecoration.Builder.init(listener)
                .setGroupBackground(resources.getColor(R.color.gray_f3f4))
                .build()
        onlineProfit_rv.addItemDecoration(decoration!!)
        onlineProfit_rv.adapter=adapter
        onlineProfit_butTime.setOnClickListener {
            (activity as ProfitRecordActivity).timePickers()
        }
    }
    private fun setRefresh(){
        hotsale_refreshimg.setImageResource(R.drawable.anim_refresh)
        val animationDrawable=hotsale_refreshimg.drawable as AnimationDrawable
        onlineProfit_smartrefresh.setOnMultiPurposeListener(object :MyMultiPurposeListener{
            override fun headerReleased() {
                animationDrawable.start()
            }

            override fun headerMoving(percent: Float) {
                setAnima(percent)
            }

            override fun headerFinish() {
                hotsale_refreshimg.setImageResource(R.drawable.refresh_0)
                animationDrawable.stop()
            }

            override fun loadMore() {
                getData(false)
            }

            override fun refresh() {
                pageIndex=1
                getData(true)
            }
        })
    }
    private fun setAnima(vlaue:Float){
        val layoutParams=hotsale_refreshimg.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.matchConstraintPercentHeight=vlaue/2
        layoutParams.dimensionRatio="0.875:1"
        hotsale_refreshimg.layoutParams=layoutParams
    }
    private fun getData(isRefresh:Boolean){
        if (pageIndex==1){
            showProgressDialog("加载中...")
        }
        val map= HashMap<String,String>()
        map["pageNo"]=pageIndex.toString()
        map["pageSize"]="10"
        map["userId"]=AppUtils.getString(Contacts.USERID, "")
        map["type"]="1"
        map["time"]=time
        RetrofitWorker.retrofitWorker.getAlreadyEarnings(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<UserEarningsBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<UserEarningsBean>) {
                        if (pageIndex==1){
                            dismissProgressDialog()
                            dataList.clear()
                        }
                        if (it.code==200){
                            if (it.data!!.records!=null&&it.data!!.records!!.isNotEmpty()){
                                if (pageIndex==1){
                                    onlineProfit_llnodata.visibility= View.GONE
                                    onlineProfit_rv.visibility= View.VISIBLE
                                    if (isRefresh){
                                        onlineProfit_smartrefresh.finishRefresh()
                                    }
                                }else{
                                    onlineProfit_smartrefresh.finishLoadMore()
                                }
                                setData(it.data!!.records!!)
                                /*if (dataList.size>=it.data!!.total.toInt()){
                                    onlineProfit_smartrefresh.finishLoadMoreWithNoMoreData()
                                }*/
                                pageIndex++
                                adapter!!.notifyDataSetChanged()
                                decoration!!.clearCache()
                            }else{
                                if (pageIndex==1&&dataList.size==0){
                                    onlineProfit_smartrefresh.finishRefresh()
                                    onlineProfit_llnodata.visibility= View.VISIBLE
                                    onlineProfit_errormsg.text="您还没有收益记录哦"
                                    onlineProfit_butTime.visibility=View.GONE
                                    onlineProfit_rv.visibility= View.GONE
                                }else{
                                    showToastMsg("没有更多数据了！")
                                }
                                onlineProfit_smartrefresh.finishLoadMoreWithNoMoreData()
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (pageIndex==1){
                            dismissProgressDialog()
                            if (isRefresh){
                                onlineProfit_smartrefresh.finishRefresh()
                                onlineProfit_smartrefresh.finishLoadMoreWithNoMoreData()
                            }
                        }
                        if (e is OtherException){
                            //showToastMsg("没有找到任何数据，换一个试试！")
                            onlineProfit_llnodata.visibility= View.VISIBLE
                            onlineProfit_errormsg.text="没有找到${time}的收益记录"
                            onlineProfit_butTime.visibility=View.VISIBLE
                            onlineProfit_rv.visibility= View.GONE
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }
                })
    }
    override fun lazyLoad() {
        getData(false)
    }
    fun refreshData(times:String){
        time=times
        pageIndex=1
        getData(true)
    }
    private fun setData(list:List<EarningsRecord>){
        val time=simpleDateFormat.format(System.currentTimeMillis())
        for (i in 0 until list.size){
            val datas=list[i]
            val times=datas.buytime
            datas.headTime=if (times==time){"本月"}else {times}
            dataList.add(datas)
        }
    }
    private inner class MyAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view= LayoutInflater.from(parent.context).inflate(R.layout.profit_record_item, parent, false)
            return MyHolder(view)
        }

        override fun getItemCount(): Int {
            return dataList.size
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (dataList.size>0){
                if (holder is MyHolder){
                    val datas=dataList[position]
                    holder.tvName!!.text=datas.nickName
                    var type=""
                    if ("4"==datas.type){
                        type="分红奖励"
                    }else {
                        type = if (-1 == datas.moneytype) {
                            "预估"
                        } else {
                            "结算"
                        }
                        var type1=""
                        when(datas.type){
                            "1"->{type1=" 自购奖励"}
                            "2"->{type1=" 团队奖励"}
                            "3"->{type1=" 平级奖励"}
                            "5"->{type1=" 推荐奖励"}
                            "6"->{type1=" 0元购补贴"}
                            "7"->{type1=" 签到奖励"}
                        }
                        type += type1
                    }
                    holder.tvType!!.text=type
                    val id=when(datas.rechargetype){
                        1->{ R.drawable.goods_tb}
                        2->{ R.drawable.goods_pdd}
                        3->{ R.drawable.goods_jd}
                        4->{ R.drawable.goods_tm}
                        else->{R.drawable.goods_tb}
                    }
                    if (datas.status=="1"){
                        holder.ivOrderType!!.visibility=View.INVISIBLE
                    }else{
                        holder.ivOrderType!!.visibility=View.VISIBLE
                    }
                    holder.faceImag!!.setImageResource(id)
                    holder.tvTime!!.text="下单时间：${datas.createTime}"
                    holder.tvPrice!!.text=datas.credit2
                }

            }
        }

    }
    private inner class MyHolder(itemview: View): RecyclerView.ViewHolder(itemview){
        var tvName:TextView?=null
        var tvType:TextView?=null
        var tvOrType:TextView?=null
        var tvContent:TextView?=null
        var tvTime:TextView?=null
        var faceImag: RoundedImageView?=null
        var tvJia:TextView?=null
        var tvPrice:TextView?=null
        var ivOrderType:ImageView?=null
        init {
            tvName=itemview.tvNikname
            tvType=itemview.onlin_tvType
            tvOrType=itemview.onlin_tvOrType
            tvTime=itemview.onlin_tvTime
            faceImag=itemview.userimag
            tvJia=itemview.onlin_tvJia
            tvPrice=itemview.tvProfitRecordMoney
            ivOrderType=itemview.ivOrderType
            tvContent=itemview.onlin_tvExplain
            tvContent!!.visibility=View.GONE
        }
    }
}